2-Dimensional Arrays in C

Introduction

A 2-dimensional array in C is an array of arrays, often used to represent matrices or grids. It stores elements in a tabular format, organized into rows and columns.

Declaration and Initialization of 2-Dimensional Array

Declaration

data_type array_name[rows][columns];

Examples

Accessing and Modifying Elements

2-D array elements are accessed using two indices:

matrix[row][column] = value; // Assigns a value to the element
int x = matrix[1][2];        // Retrieves the element at row 1, column 2
            

Example: Iterating Through a 2-D Array

#include < stdio.h>

int main() {
    int matrix[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };

    // Printing the 2-D array
    for (int i = 0; i < 2; i++) {           // Iterate through rows
        for (int j = 0; j < 3; j++) {       // Iterate through columns
            printf("matrix[%d][%d] = %d\n", i, j, matrix[i][j]);
        }
    }

    return 0;
}
            

Output:

matrix[0][0] = 1
matrix[0][1] = 2
matrix[0][2] = 3
matrix[1][0] = 4
matrix[1][1] = 5
matrix[1][2] = 6
            

Memory Layout

In C, 2-D arrays are stored in row-major order, meaning that elements in the same row are stored in contiguous memory locations.

int matrix[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};
            

Stored in memory as:

1, 2, 3, 4, 5, 6

Passing 2-D Arrays to Functions

When passing a 2-D array to a function, the number of columns must be specified, but the number of rows is optional.

#include  < stdio.h>

void printMatrix(int rows, int cols, int matrix[rows][cols]) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int matrix[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };

    printMatrix(2, 3, matrix); // Pass the array to the function
    return 0;
}
            

Common Use Cases